import React, { Component, Fragment } from 'react';
import router from 'umi/router';
import { connect } from 'dva';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import moment from 'moment'; //time格式工厂
import { FormattedMessage, formatMessage } from 'umi/locale'; //此方法引入的数据可以在src/locales中配置
import ImportModal from '../ImportModal/index.js';
import UpdateModal from '../UpdateModal/index.js';
import DetailModal from '../DetailModal/index.js';
import {
  Input,
  DatePicker,
  Form,
  Row,
  Col,
  Spin,
  Card,
  PageHeader,
  Alert,
  message,
  Icon,
  Tree,
  Divider,
  TreeSelect,
  Tooltip,
  Checkbox,
  Empty,
  Popover,Select,Button , Table ,Modal,Pagination
} from 'antd';

//日期插件
const { MonthPicker, RangePicker } = DatePicker;
const dateFormat = 'YYYY-MM-DD';
const TreeNode = TreeSelect.TreeNode;
//表单
const FormItem = Form.Item;

//所属租户选择框
const Option = Select.Option;

@connect(({ userManage, loading }) => ({
  userManage,
  loading: loading.models.userManage,
}))
@Form.create()
class List extends Component {
  componentDidMount() {
    //在第一次渲染之后
    const { dispatch } = this.props;
    dispatch({
      type: 'userManage/fetch',
      payload: { page_num: 1, page_size: 10 },
    });
  }
  initialization = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'userManage/fetch',
      payload: { page_num: 1, page_size: 10 },
    });
    this.props.form.resetFields();
  };



  deleteUser = (id, source, ext_user_id) => {
    const {
      dispatch,
      userManage: { pagination },
    } = this.props;
    const props = this.props;
    const { userManage, form } = this.props;
    const _this = this;
    Modal.confirm({
      title: '确认删除吗',
      content: '您确定要删除这条数据吗？',
      okText: '确认',
      cancelText: '取消',
      icon: 'frown',
      onOk() {
        //发送删除请求
        props
          .dispatch({
            type: 'userManage/deleteUser',
            payload: {
              user_id: id,
              source: source,
              ext_user_id: ext_user_id,
            },
          })
          .then(r => {
            if (r) {
              _this.handleTableChange(pagination, null, null);
            }
          });
      },
      onCancel() {
        return false;
      },
    });
  };
  createUser = payload => {
    const { dispatch } = this.props;
    dispatch({
      type: 'userManage/createUser',
      payload: {
        ...payload,
      },
    }).then(r => {
      if (r) {
        this.initialization();
      }
    });
  };
  updateUser = payload => {
    const {
      dispatch,
      userManage: { pagination },
    } = this.props;
    dispatch({
      type: 'userManage/updateUser',
      payload: {
        ...payload,
      },
    }).then(r => {
      if (r) {
        this.handleTableChange(pagination, null, null);
      }
    });
  };

  //关闭新增/修改模态框
  closeUpdateModal = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'userManage/save',
      payload: {
        updateModalVisibel: false,
      },
    });
  };

  //显示新增/修改模态框
  showUpdateModal = (modal_type, record) => {
    const { dispatch } = this.props;
    if (modal_type === 'create') {
      dispatch({
        type: 'userManage/showUpdateModal',
        payload: {
          modal_type: modal_type,
        },
      });
    } else if (modal_type === 'update') {
      dispatch({
        type: 'userManage/showUpdateModal',
        payload: {
          modal_type: modal_type,
          user_id: record.user_id,
        },
      });
    }
  };

  //关闭详情
  closeDatailModal = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'userManage/save',
      payload: {
        detailData: undefined,
        detailModalVisibel: false,
      },
    });
  };
  //显示详情
  showDetail = values => {
    const user_id = values.user_id;
    this.props.dispatch({
      type: `userManage/showDetail`,
      payload: {
        user_id: user_id,
      },
    });
  };
  //分页
  handleTableChange = (pagination, filters, sorter) => {
    const {
      form: { getFieldsValue },
    } = this.props;

    let fields = getFieldsValue();


    const values = {
      ...fields,
      page_num: pagination.current,
      page_size: pagination.pageSize,
    };
    const { dispatch } = this.props;
    dispatch({
      type: 'userManage/findUserList',
      payload: values,
    });
  };
  //查询方法
  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      let fields = fieldsValue;
      if (fields.create_time && fields.create_time.length > 0) {
        fields.created_time_from = moment(fields.create_time[0]).format('YYYY-MM-DD HH:mm:00');
        fields.created_time_to = moment(fields.create_time[1]).format('YYYY-MM-DD HH:mm:59');
      }
      delete fields.create_time;
      const values = {
        ...fields,
        page_num: 1,
        page_size: 10,
      };

      dispatch({
        type: 'userManage/findUserList',
        payload: values,
      });
    });
  };



  //表单重置
  handleReset = () => {
    this.props.form.resetFields();
  };
  renderSimpleForm() {
    const { getFieldDecorator } = this.props.form;
    const {
      userManage: {  },
      dispatch,
    } = this.props;

    return (
      /*查询表单部分*/
      <Form onSubmit={this.handleSearch} layout="inline">
        <div
          style={{
            fontSize: '16px',
            marginBottom: '15px',
          }}
        >
          <div style={{ height: 50 }}>
            <Row align="middle">
              <Col xl={8} lg={12} sm={24} align="left" style={{ marginTop: 13 }}>
                <div style={{ marginTop: '2px', marginRight: '4px', display: 'inline-block' }}>
                  用户名 :
                </div>
                {getFieldDecorator('user_nick_name', {
                  validateTrigger: ['onChange', 'onBlur'],
                  rules: [],
                })(<Input placeholder="请输入" style={{ width: '70%' }} allowClear />)}
              </Col>
            </Row>
          </div>
          <Row gutter={12}>
            <Col md={24} sm={24} style={{ paddingBottom: 15 }}>
              <div
                style={{
                  display: 'flex',
                  justifyContent: 'space-between',
                  flexWrap: 'wrap',
                  marginTop: 11,
                }}
              >
                <div>
                  <Button type="primary" onClick={() => this.showUpdateModal('create', null)}>
                    新建
                  </Button>
                </div>
                <div>
                  <Button type="primary" htmlType="submit">
                    查询
                  </Button>
                  <Button style={{ marginLeft: 8 }} onClick={this.handleReset}>
                    重置
                  </Button>
                </div>
              </div>
            </Col>
          </Row>
        </div>
      </Form>
    );
  }

  render() {
    const { userManage, form } = this.props;
    const {
      pagination,
      user_list,

      detailData,
      detailModalVisibel,
      updateData,
      modal_type,
      updateModalVisibel,
    } = userManage;

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: total =>
        `总共 ${parseInt(pagination.total)} 条数据 第 ${parseInt(pagination.current)} 页`,
      ...pagination,
    };

    const columns = [
      {
        title: "用户名",
        dataIndex: 'user_nick_name',
        key: 'user_nick_name',
        /*render: (text, record) => {
          return <a onClick={() => this.showDetail(record)}>{record.user_nick_name}</a>;
        },*/
        align: 'center',
      },
      {
        title: "性别",
        key: 'sex',
        dataIndex: 'sex',
        align: 'center',
        render :(text,record)=>{
          return text==='1'?'男':text==='2'?'女':''
        }
      },
      {
        title: "生日",
        key: 'birthday',
        dataIndex: 'birthday',
        align: 'center',
        render :(text,record)=>{
          return text?moment(text).format('YYYY-MM-DD HH:mm:00'):''
        }
      },
      {
        title: "电话号",
        key: 'phone',
        dataIndex: 'phone',
        align: 'center',
      },
      {
        title: '操作',
        key: 'doIt',
        fixed: 'right',
        dataIndex: 'doIt',
        width: '250px',
        render: (text, record) => (
          <span className="table-operation">
            <a onClick={() => this.showUpdateModal('update', record)}>编辑</a>
            <Divider type="vertical" />
            <a onClick={() => this.deleteUser(record.user_id, record.source, record.ext_user_id)}>
              删除
            </a>
          </span>
        ),
        align: 'center',
      },
    ];
    return (
      <PageHeaderWrapper>
        <div
          style={{
            backgroundColor: '#FFFFFF',
            paddingLeft: '5%',
            paddingRight: '5%',
          }}
        >
          {this.renderSimpleForm()}
          {user_list && user_list.length > 0 ? (
            <Table
              onChange={this.handleTableChange}
              pagination={paginationProps}
              scroll={{ x: 1400 }}
              columns={columns}
              dataSource={user_list}
              rowKey={record => record.user_id}
            />
          ) : (
            <Empty style={{ paddingBottom: 30, paddingTop: 15 }} />
          )}

          {updateModalVisibel ? (
            <UpdateModal
              modalFlag={modal_type}
              updateData={updateData}

              closeUpdateModal={this.closeUpdateModal}
              createUser={this.createUser}
              updateUser={this.updateUser}
            />
          ) : (
            []
          )}
          {detailModalVisibel ? (
            <DetailModal detailData={detailData} closeDatailModal={this.closeDatailModal} />
          ) : (
            []
          )}
        </div>
      </PageHeaderWrapper>
    );
  }
}
export default List;
